/**
 * 1、添加模块
 * 2、更新消息提示
 * 周涛：2020-05-25
 */
'use strict';
const db = uniCloud.database()
const dbCmd = db.command;
exports.main = async (event, context) => {
  let {projectID,userID,fileName,fileUrl,time} = event;
  let curUserData = {}; // 当前操作的用户
  let projectInDB = await db.collection('projects').doc(projectID).get();
  
  if(projectInDB.data.length !== 0 || projectInDB.affectedDocs !== 0){
	  curUserData = projectInDB.data[0].partners.filter(item=>{
		  return item.userID === userID
	  })
	  
	  // 删除
	  let removePartner = await db.collection('projects').doc(projectID).update({
		  partners:dbCmd.pull({
			userID
		  })
	  })
	  
	  // 重新追加
	  curUserData[0].finishProjectDoc = {fileName,fileUrl,time}
	  let addPartner = await db.collection('projects').doc(projectID).update({
		  partners:dbCmd.push(curUserData)
	  })
	  
	  // 更新用户消息提示(header栏的上传模块消息提示)
	  let havePartnerMsg = projectInDB.data[0].partnerChangeUploadModule.some(item=>{
		  return item.userID === userID
	  })
	  if(havePartnerMsg){ // 已经存在 将其删除
		  let removePartnerMsg = await db.collection('projects').doc(projectID).update({
			  partnerChangeUploadModule:dbCmd.pull({
				userID  
			  })
		  })
	  }
	  let updateMsgTips = await db.collection('projects').doc(projectID).update({
		 partnerChangeUploadModule:dbCmd.push({
			userData:curUserData,
			projectID,
			userID,
			fileName,
			time:Date.now()
		 })
	  })
	  
	  return {
		  status:0,
		  msg:"添加成功"
	  }
  }
  
  return {
	  status:-1,
	  msg:"稍后重试"
  }
};
